<template>
  <div class="formulaManage-add-update-component">
    <el-dialog
      v-if="modelValue.visible"
      v-model="modelValue.visible"
      :title="
        !modelValue.form.id
          ? `新增${modelValue.title}`
          : `修改${modelValue.title}`
      "
      width="940px"
    >
      <el-steps
        style="width: 100%; margin-top: 10px"
        :active="active"
        align-center
        finish-status="success"
      >
        <el-step title="基本资料" />
        <el-step title="制作步骤" />
        <el-step title="标准配方" />
        <el-step title="选项配置" />
        <el-step title="变动规则" />
      </el-steps>
      <div style="padding-right: 50px; padding: 20px; padding-top: 30px">
        <el-form
          :model="modelValue.form"
          :rules="modelValue.rules"
          ref="addEditRef"
          :label-width="100"
        >
          <div v-if="active === 0">
            <div class="form-item">
              <el-form-item label="配方编码" prop="number">
                <el-input
                  style="width: 280px"
                  placeholder="请输入配方编码"
                  v-model="modelValue.form.number"
                  autocomplete="off"
                  :disabled="!!modelValue.form.id"
                />
              </el-form-item>
              <el-form-item label="配方名称" prop="name">
                <el-input
                  style="width: 280px"
                  placeholder="请输入配方名称"
                  v-model="modelValue.form.name"
                  autocomplete="off"
                />
              </el-form-item>
            </div>
            <div class="form-item">
              <el-form-item label="外部配方编码" prop="orNumber">
                <el-input
                  style="width: 152px"
                  placeholder="请输入外部配方编码"
                  v-model="modelValue.form.orNumber"
                  autocomplete="off"
                />
                <el-button
                  @click="selectOutNumberStatus"
                  type="primary"
                  style="margin-left: 12px"
                  >选择外部配方</el-button
                >
              </el-form-item>
              <el-form-item
                v-if="outNumberStatus"
                label="选择外部编码"
                prop="orNumber"
              >
                <el-select
                  style="width: 280px"
                  v-model="modelValue.form.orCategoryId"
                  placeholder="选择外部编码"
                >
                  <el-option
                    v-for="option in orNumberList"
                    :key="option.id"
                    :label="option.name"
                    :value="option.id"
                  />
                </el-select>
              </el-form-item>
            </div>
            <div class="form-item">
              <el-form-item label="配方分类" prop="categoryId">
                <el-select
                  style="width: 280px"
                  v-model="modelValue.form.categoryId"
                  placeholder="选择配方分类"
                >
                  <el-option
                    v-for="option in modelValue.formulaCategoryList"
                    :key="option.id"
                    :label="option.name"
                    :value="option.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="状态" prop="enabled">
                <el-select
                  style="width: 280px"
                  v-model="modelValue.form.enabled"
                  placeholder="选择状态"
                >
                  <el-option
                    v-for="option in statusOptions"
                    :key="option.id"
                    :label="option.name"
                    :value="option.id"
                  />
                </el-select>
              </el-form-item>
            </div>
            <el-form-item label="备注" prop="remark">
              <el-input
                style="width: 694px"
                type="textarea"
                :rows="3"
                placeholder="请输入备注内容"
                v-model="modelValue.form.remark"
                autocomplete="off"
              />
            </el-form-item>
          </div>
          <div v-if="active === 1">
            <div style="margin-bottom: 12px">
              <el-button @click="addStep" type="primary"
                >新增制作步骤</el-button
              >
            </div>
            <div>
              <el-table
                :data="makeStepDataList"
                border
                stripe
                style="width: 100%"
              >
                <el-table-column prop="id" label="步骤" width="100" />
                <el-table-column prop="step" label="物料">
                  <template #default="scope">
                    <div v-if="scope.row.status == 0">
                      <el-select
                        v-model="scope.row.materialIdList"
                        placeholder="请选择物料"
                        style="width: 100%"
                        multiple
                        @change="changeMaterialList(scope.row)"
                      >
                        <el-option
                          v-for="option in modelValue.materialConfigList"
                          :key="option.id"
                          :label="option.name"
                          :value="option.id"
                        />
                      </el-select>
                    </div>
                    <div v-else>
                      <el-tag
                        v-for="item in scope.row.materialList"
                        :key="item.id"
                        style="margin-right: 5px"
                      >
                        {{ item.name }}
                      </el-tag>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="160px" fixed="right">
                  <template #default="scope">
                    <!-- v-if="rolePermission.editRolePerm" -->
                    <el-button
                      v-if="scope.row.status == 0"
                      type="success"
                      size="small"
                      @click.prevent="editStep(scope.row, 2)"
                      >确定</el-button
                    >
                    <el-button
                      v-if="scope.row.status == 1"
                      type="primary"
                      size="small"
                      @click.prevent="editStep(scope.row, 2)"
                      >编辑</el-button
                    >
                    <!-- v-if="rolePermission.removeRolePerm" -->
                    <el-button
                      type="danger"
                      size="small"
                      @click.prevent="removeStep(scope.row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <div v-if="active === 2">
            <el-table
              :data="stdFormulaDataList"
              border
              stripe
              style="width: 100%"
            >
              <el-table-column prop="step" label="步骤" width="60" />
              <el-table-column prop="index" label="出料顺序" width="110">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.index"
                    :min="1"
                    :max="1024"
                    size="small"
                    style="width: 80px"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="name" label="物料"> </el-table-column>
              <el-table-column prop="value" label="标准量" width="110px">
                <template #default="scope">
                  <el-input-number
                    v-model="scope.row.value"
                    :min="0"
                    :max="1024"
                    size="small"
                    style="width: 80px"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="unitName" label="单位" width="60">
              </el-table-column>
              <el-table-column
                prop="temperatureRequirederatur"
                label="是否需要温度"
                width="110"
              >
                <template #default="scope">
                  <el-checkbox
                    v-model="scope.row.temperatureRequired"
                  ></el-checkbox>
                </template>
              </el-table-column>
              <el-table-column
                prop="temperatureScope"
                label="温度范围(最低温度-最高温度)"
                width="230"
              >
                <template #default="scope">
                  <div v-if="scope.row.temperatureRequired">
                    <el-input-number
                      v-model="scope.row.minTemperature"
                      :min="-100"
                      :max="100"
                      size="small"
                      style="width: 80px"
                    />
                    -
                    <el-input-number
                      v-model="scope.row.maxTemperature"
                      :min="-100"
                      :max="100"
                      size="small"
                      style="width: 80px"
                    />
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div v-if="active === 3">
            <el-form-item label="可选规格" prop="orNumber">
              <el-select
                v-model="modelValue.form.specificationIds"
                placeholder="请选择可选规格"
                style="width: 100%"
                multiple
                @change="
                  changeSpecificationList(modelValue.form.specificationIds)
                "
              >
                <template #label="{ label, value }">
                  <span>{{ value }} - </span>
                  <span>{{ label }}</span>
                </template>
                <el-option
                  v-for="option in modelValue.specificationConfigAllList"
                  :key="option.number"
                  :label="option.name"
                  :value="option.number"
                />
              </el-select>
            </el-form-item>
            <div
              class="specification-item"
              v-for="item in specificationList"
              :key="item.id"
            >
              <!-- 标题 -->
              <div class="title">{{ item.name }}</div>
              <div>
                <!-- 可选规格 -->
                <el-button-group class="ml-4">
                  <el-button
                    class="select"
                    :type="row.selected ? 'primary' : 'default'"
                    v-for="row in item.list"
                    :key="row.id"
                    @click="selectDefaultSpecification(row)"
                  >
                    {{ row.name }}</el-button
                  >
                </el-button-group>
              </div>
              <div class="detail">
                <div style="margin-right: 4px">默认规格:</div>
                <el-select
                  size="small"
                  style="width: 160px"
                  v-model="item.defaultSelectedId"
                  placeholder="请选择默认规格"
                >
                  <el-option
                    v-for="option in item.list.filter((row) => row.selected)"
                    :key="option.id"
                    :label="option.name"
                    :value="option.id"
                  />
                </el-select>
                <div class="checkbox">
                  <el-checkbox v-model="item.enableCustomize"
                    >是否支持客制化用料选择</el-checkbox
                  >
                  <el-select
                    v-if="item.enableCustomize"
                    size="small"
                    style="width: 160px; margin-left: 6px"
                    v-model="item.bbb"
                    placeholder="支持客制化的物料"
                  >
                    <el-option
                      v-for="option in stdFormulaDataList"
                      :key="option.id"
                      :label="option.name"
                      :value="option.id"
                    />
                  </el-select>
                </div>
              </div>
            </div>
          </div>
          <div v-if="active === 4">
            <div class="rule-section">
              <h1 class="title">添加新的变动规则</h1>
              <div class="first-content-field">
                <el-form-item
                  v-for="item in specificationList"
                  :key="item.id"
                  :label-width="120"
                  style="margin-bottom: 4px"
                  :label="item.name"
                  prop=""
                >
                  <!-- v-model=""  -->
                  <el-radio-group v-model="item.ruleSelectId" size="small">
                    <el-radio-button
                      v-for="subItem in item.list"
                      :key="subItem.id"
                      :label="subItem.name"
                      :value="subItem.id"
                    />
                  </el-radio-group>
                </el-form-item>
                <el-form-item
                  style="margin-top: 6px"
                  :label-width="120"
                  label=""
                  prop="orNumber"
                >
                  <el-button
                    @click="addRulesForStep5"
                    type="success"
                    size="small"
                    >+ 添加规则</el-button
                  >
                </el-form-item>
              </div>
            </div>
            <div class="rule-section">
              <div class="title-field">
                <h1 class="title">已添加的变动规则</h1>
                <el-select
                  style="width: 80%"
                  size="small"
                  placeholder="请选择配置项"
                  multiple
                  v-model="selectedRules"
                  @change="handleFilterChange"
                  @remove-tag="handleRemoveFilterChange"
                >
                  <el-option-group
                    v-for="group in specificationList"
                    :key="group.name"
                    :label="group.name"
                  >
                    <el-option
                      v-for="item in group.list"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-option-group>
                </el-select>
              </div>
              <div class="content-field change-rule">
                <div class="left">
                  <div
                    v-for="(ruleItems, ruleItemIndex) in rulesFilterForStep5"
                    @click="changeLeftItemOfStep5(ruleItems)"
                    :key="ruleItemIndex"
                    class="rule-item"
                    :class="{ selected: ruleItems.selected }"
                  >
                    <img
                      class="remove-icon"
                      src="@/assets/images/remove.png"
                      alt=""
                      @click.stop="removeLeftItem(ruleItemIndex)"
                    />
                    <div v-for="ruleItem in ruleItems.left" :key="ruleItem.id">
                      <div>
                        <el-tag style="margin-bottom: 3px">{{
                          ruleItem.name
                        }}</el-tag>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="right" style="overflow: hidden">
                  <!-- :data="tableData" -->
                  <el-table
                    border
                    :data="rightItemData.right"
                    stripe
                    size="small"
                    v-if="ruleSelectOfStep5"
                  >
                    <el-table-column prop="seq" label="步骤号" width="65" />
                    <el-table-column prop="sort" label="优先级" width="65" />
                    <el-table-column prop="name" label="物料" min-width="150">
                      <template #default="scope">
                        {{ scope.row.name || scope.row.materialName }}
                      </template>
                    </el-table-column>
                    <el-table-column prop="operate" label="修改" width="100">
                      <template #default="scope">
                        <el-select
                          v-model="scope.row.operate"
                          placeholder="选择"
                          size="small"
                          @change="handleOperateChange(scope.row)"
                        >
                          <el-option
                            v-for="item in operateOptions"
                            :label="item.label"
                            :value="item.value"
                            :id="item.value"
                            :key="item.value"
                          >
                          </el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="name"
                      label="百分比/固定值"
                      width="110"
                    >
                      <template #default="scope">
                        <el-select
                          :disabled="scope.row.operate == '3'"
                          v-model="scope.row.valueType"
                          placeholder="选择"
                          size="small"
                          @change="handleValueTypeChange(scope.row)"
                        >
                          <el-option
                            v-for="item in valueTypeOptions"
                            :label="item.label"
                            :value="item.value"
                            :id="item.value"
                            :key="item.value"
                          >
                          </el-option>
                        </el-select>
                      </template>
                    </el-table-column>
                    <el-table-column prop="value" label="数值" width="110">
                      <template #default="scope">
                        <el-input-number
                          v-model="scope.row.extralValue"
                          :min="0"
                          :max="1024"
                          size="small"
                          style="width: 90px"
                          @change="handleExtralValueChange(scope.row)"
                        />
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="actualValue"
                      label="实际用量"
                      width="75"
                    >
                      <template #default="scope">
                        {{ scope.row.finalValue || 0 }}g
                      </template>
                    </el-table-column>
                  </el-table>
                  <el-input
                    v-if="ruleSelectOfStep5"
                    v-model="rightItemData.remark"
                    style="width: 100%; margin-top: 12px"
                    :row="3"
                    type="textarea"
                    placeholder="请说明辅助内容"
                  />
                </div>
              </div>
              <!-- rulesForStep5 -->
            </div>
          </div>
        </el-form>
      </div>
      <template #footer v-if="!modelValue.form.disabled">
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button :disabled="active <= 0" type="primary" @click="prev">
            上一步
          </el-button>
          <el-button :disabled="active >= 4" type="primary" @click="next">
            下一步
          </el-button>
          <el-button type="success" @click="ensure"> 保存并返回 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import {
  addFormulamanage,
  updateFormulamanage,
} from '@/api/fms-formula-manage.api'
import { statusOptions } from '@/utils/common.utils'

const props = defineProps(['modelValue'])
const addEditRef = ref<FormInstance>()
const active = ref(0)
const orNumberList = ref([])
const operateOptions = [
  {
    label: '增加',
    value: 1,
  },
  {
    label: '减少',
    value: 2,
  },
  {
    label: '替换',
    value: 3,
  },
]
const valueTypeOptions = [
  {
    label: '固定值',
    value: 1,
  },
  {
    label: '百分比',
    value: 2,
  },
]
const ruleSelectOfStep5 = ref(false)
const selectedRules = ref([])
let lastSelectedIds = []
const handleRemoveFilterChange = (value: any) => {
  lastSelectedIds = lastSelectedIds.filter((item) => item != value)
  handleFilterChange(lastSelectedIds)
}

const handleFilterChange = (newSelected: any) => {
  lastSelectedIds = newSelected

  //
  const groupSelectionSet = new Set()

  newSelected = newSelected.reverse()

  let filterSelected: Array<number> = []
  // 遍历新选中的项，记录每个分组的选择
  newSelected.forEach((item: any) => {
    // 找到该项所属的分组
    let group = specificationList.value.find((g) =>
      g.list.some((spec: any) => spec.id === item)
    )

    if (!groupSelectionSet.has(group)) {
      filterSelected.push(item)
      groupSelectionSet.add(group)
    }
  })

  /***
   * 对下面的列表进行过滤
   */
  rulesFilterForStep5.value = []
  for (let ruleItems of rulesForStep5.value) {
    let includeFlag = true
    let subList = ruleItems.left || []
    for (let ruleItem of subList) {
    }
  }

  //获取到了所有过滤条件
  selectedRules.value = filterSelected
  handleFliterForStep5()
}

/***
 * 第五步 添加变动规则
 */
const rulesForStep5 = ref<Array<any>>([])
const rulesFilterForStep5 = ref<Array<any>>([])
const addRulesForStep5 = () => {
  let specifications = specificationList.value || []
  let subList: any = []
  for (let item of specifications) {
    if (!item.ruleSelectId) {
      continue
    }

    let findRes = item.list.find((row: any) => row.id === item.ruleSelectId)
    if (findRes) {
      subList.push({
        id: findRes.id,
        number: findRes.number,
        name: findRes.name,
      })
    }
    item.ruleSelectId = ''
  }

  if (subList.length == 0) {
    ElMessage.warning('请选择规格项')
    return
  }

  /***
   * 如果 subList 已经存在，则不添加，并提示
   */
  for (let item of rulesForStep5.value) {
    let isExist = true
    let leftItem = item.left || []

    //数量不一致，则一定不相等。
    if (leftItem.length != subList.length) {
      continue
    }

    //数量一致，如果对比发现存在不同
    for (let i = 0; i < leftItem.length; i++) {
      let subItem = subList[i]
      let newItem = leftItem[i]
      if (subItem.id != newItem.id) {
        isExist = false
        break
      }
    }

    if (isExist) {
      ElMessage.error('规则项已存在')
      return
    }
  }

  let data = stdFormulaDataList.value
  rulesForStep5.value.push({
    left: subList,
    right: JSON.parse(JSON.stringify(data)),
  })

  handleFliterForStep5()
  //过滤条件
}

const handleFliterForStep5 = () => {
  let list = rulesForStep5.value
  let ruleIds = selectedRules.value
  rulesFilterForStep5.value = []

  //list 的 left 中元素，必须全部包含 ruleIds 中的元素。
  for (let item of list) {
    let leftList = item.left || []
    let leftIdSet = new Set()
    for (let leftItem of leftList) {
      leftIdSet.add(leftItem.id)
    }

    let includeFlag = true
    for (let ruleId of ruleIds) {
      if (!leftIdSet.has(ruleId)) {
        includeFlag = false
        break
      }
    }

    if (includeFlag) {
      rulesFilterForStep5.value.push(item)
    }
  }
}

const removeLeftItem = (ruleItemIndex) => {
  /***
   * 如果删掉的是本身选中状态的 left item。
   */
  let list = rulesForStep5.value || []
  let item = list[ruleItemIndex]
  if (item.selected) {
    ruleSelectOfStep5.value = false
  }
  list = list.filter((item, index) => {
    return index !== ruleItemIndex
  })

  rulesForStep5.value = list
  handleFliterForStep5()
}

/***
 * 选择了左边的规格项
 */
// const curRightTableData = ref([]);
// const curRightMarkData = ref("");
const rightItemData = ref({
  curRightTableData: '',
  remark: '',
})
const changeLeftItemOfStep5 = (ruleItems: any) => {
  rulesForStep5.value.forEach((item: any) => {
    item.selected = false
  })
  ruleItems.selected = true

  if (!ruleItems.remark) {
    ruleItems.remark = ''
  }

  rightItemData.value = ruleItems || {}
  ruleSelectOfStep5.value = true
}

const handleOperateChange = (row) => {
  // (1) 修改方式
  // row.operate
  // (2) 百分比/固定值
  // row.valueType
  // (3) 数值
  // row.extralValue
  calculateFinalValue(row)
  //finalValue
}

const handleValueTypeChange = (row) => {
  calculateFinalValue(row)
}

const handleExtralValueChange = (row) => {
  calculateFinalValue(row)
}

const calculateFinalValue = (row: any) => {
  //固定值
  let extralValue = row.extralValue
  //增加
  if (row.operate == '1') {
    if (row.valueType == '1') {
      row.finalValue = extralValue + row.value
    } else {
      row.finalValue = (extralValue / 100 + 1) * row.value
      row.finalValue = row.finalValue.toFixed(2)
    }
  } else if (row.operate == '2') {
    if (row.valueType == '1') {
      row.finalValue = row.value - extralValue < 0 ? 0 : row.value - extralValue
    } else {
      row.finalValue = (1 - extralValue / 100) * row.value
      row.finalValue = row.finalValue.toFixed(2)
    }
  } else {
    row.finalValue = extralValue
  }
}

//=============================================================

onMounted(() => {
  active.value = 0
  /***
   * 需要判断是新增，还是修改
   */

  let form = props.modelValue.form || {}
  if (form.id) {
    //处理 steps
    let productSteps = form.productSteps || []
    let makeStepDatas = []
    let seq = 0
    while (productSteps.length > 0) {
      let subList = productSteps.filter((row: any) => {
        return row.seq == seq
      })
      let item: any = {}
      if (subList.length > 0) {
        item.id = subList[0].seq
        item.materialIdList = subList.map((row: any) => {
          return row.materialId
        })
        item.materialList = subList.map((row: any) => {
          row.name = row.materialName
          row.id = row.materialId
          row.unitName = row.materialUnitName
          return row
        })
        item.status = 0
      }
      productSteps = productSteps.filter((row: any) => {
        return row.seq != seq
      })
      if (subList.length > 0) {
        makeStepDatas.push(item)
      }
      seq = Number(seq) + 1
    }

    makeStepDataList.value = makeStepDatas

    //处理 productSpecGroups
    let productSpecGroups = form.productSpecGroups || []
    let specificationIds = form.specificationIds || []
    changeSpecificationList(specificationIds, productSpecGroups)

    /***
     * 处理 productRules
     */
    let productRules = form.productRules || []
    let newProductRuels = []
    const groupMap = new Map<string, any[]>()
    productRules.forEach((item: any) => {
      const condition = item.ruleCondition
      if (!groupMap.has(condition)) {
        groupMap.set(condition, [])
      }

      //处理 sort
      item.sort = item.stepSeq
      //处理 value
      groupMap.get(condition)?.push(item)
    })

    let keys = groupMap.keys()
    const regex = /(?<=\b|')\d{19}(?=\b|'|&)/g

    let subList = []
    for (let item of specificationList.value) {
      if (Array.isArray(item.list)) {
        subList.push(...item.list)
      }
    }
    for (let key of keys) {
      let leftKeyItems = key.match(regex) || []
      let leftItems = leftKeyItems.map((item) => {
        let findItem = subList.find((row) => {
          return item == row.id
        })
        if (findItem) {
          return {
            id: findItem.id,
            number: findItem.number,
            name: findItem.name,
          }
        }
        return {}
      })
      newProductRuels.push({
        left: leftItems,
        right: groupMap.get(key),
      })
    }
    rulesForStep5.value = newProductRuels || []
    rulesFilterForStep5.value = rulesForStep5.value
  } else {
    //新增
    makeStepDataList.value = []
  }
})

const outNumberStatus = ref(false)
const selectOutNumberStatus = () => {
  outNumberStatus.value = true
}

//==========================================
const makeStepDataList = ref<any>([])
const stdFormulaDataList = ref<any>([])
//可选规格
const specificationList = ref<any>([])
const selectDefaultSpecification = (dataItem: any) => {
  if (!dataItem.selected) {
    dataItem.selected = true
    return
  }
  dataItem.selected = false
}
const changeSpecificationList = (dataItem: any, productSpecGroups = []) => {
  let specificationConfigAllList =
    props.modelValue.specificationConfigAllList || []

  //选出已经选中的。
  let dataList = dataItem.map((item: any) => {
    let findRes = specificationConfigAllList.find((row: any) => {
      return item == row.number
    })
    findRes.list = findRes.children || []

    let findRes_match: any = productSpecGroups.find((row: any) => {
      return row.number == item
    })
    if (findRes && findRes_match) {
      findRes.list = findRes.list.map((item: any) => {
        item.selected = true
        return item
      })
      findRes.defaultSelectedId = findRes_match.defaultSelectedId
      findRes.enableCustomize = findRes_match.enableCustomize ? true : false
    }
    return findRes
  })

  /***
   * 处理重新选中之后会附带的规格
   */
  let excludeSpecificationConfigs = specificationConfigAllList.filter(
    (item: any) => {
      let findRes = dataItem.find((row: any) => {
        return row == item.number
      })
      return !findRes
    }
  )
  for (let item of excludeSpecificationConfigs) {
    item.enableCustomize = false
    item.defaultSelectedId = ''
    item.selected = false
  }

  specificationList.value = dataList
  console.log('changeSpecificationList: ', specificationList.value)
}

const changeMaterialList = (dataItem: any) => {
  let materialIdList = dataItem.materialIdList || []
  console.log('dataItem.materialList: ', materialIdList)

  dataItem.materialList = materialIdList.map((item: any) => {
    let findRes = props.modelValue.materialConfigList.find(
      (row: any) => row.id == item
    )
    return findRes
  })

  console.log('dataItem.materialList: ', dataItem)
}

const addStep = () => {
  let newId = makeStepDataList.value.length + 1
  makeStepDataList.value.push({
    id: newId,
    materialIdList: [],
    materialList: [],
    status: 0,
  })
}
const editStep = (item: any) => {
  item.status = item.status ? 0 : 1
}
const removeStep = (item: any) => {
  makeStepDataList.value = makeStepDataList.value.filter((row: any) => {
    return item.id !== row.id
  })
}

//==========================================

//==========================================
const prev = () => {
  if (active.value > 0) {
    active.value--
  }
}

const filterOptions = ref([])
// specificationList
const next = () => {
  //开始进入到第二步
  active.value++

  if (active.value === 2) {
    //收集数据
    let dataList = makeStepDataList.value.reduce(
      (first: Array<any>, last: any, index: number) => {
        let itemList = last.materialList || []
        first.push(
          ...itemList.map((item: object, itemIndex: number) => {
            let value = item.value || 0
            return {
              ...item,
              index: item.index || itemIndex + 1,
              value: value,
              step: item.step || index + 1,
              minTemperature: item.minTemperature,
              maxTemperature: item.maxTemperature,
              unitName: item.materialUnit,
              temperatureRequired: item.temperatureRequired ? true : false,
              extralValue: 0,
              finalValue: value,
              valueType: 1,
              operate: 1,
            }
          })
        )
        return first
      },
      []
    )
    stdFormulaDataList.value = dataList
    console.log('stdFormulaDataList.value: ', stdFormulaDataList.value)
  } else if (active.value === 4) {
    //to do
    // alert(JSON.stringify(specificationList.value))
    let list = specificationList.value || []
    let newList = []
    for (let i = 0; i < list.length; i++) {
      let item = list[i]
      let children = item.children || []
      let options = children.map((row: any) => {
        return {
          value: row.id,
          label: row.name,
        }
      })
      newList.push({
        label: item.name,
        options,
      })
    }
    filterOptions.value = newList
  }
}
/***
 * 确认弹框
 */
const ensure = () => {
  let form = props.modelValue.form
  let formData: any = {
    //名称
    name: form.name,
    //编号
    number: form.number,
    orNumber: form.orNumber,
    orCategoryId: form.orCategoryId,
    //类型编号
    categoryId: form.categoryId,
    isBaseline: 1,
    //是否开启
    enabled: form.enabled,
    remark: form.remark,
  }

  let productSteps = []
  for (let itemIndex in makeStepDataList.value) {
    let item = makeStepDataList.value[itemIndex]
    let materialList = item.materialList || []
    for (let rowIndex in materialList) {
      let row = materialList[rowIndex]
      productSteps.push({
        //产品编号
        value: item.value || 0,
        temperatureRequired: item.temperatureRequired ? 1 : 0 || 0,
        maxTemperature: item.maxTemperature || 0,
        minTemperature: item.minTemperature || 0,
        seq: Number(itemIndex) + 1,
        sort: Number(rowIndex) + 1,
        materialId: row.materialId || row.id,
        materialName: row.materialName || row.name,
        materialUnit: row.materialUnit || row.unitName,
        productId: form.id,
      })
    }
  }
  formData.productSteps = productSteps

  //统计是否温度，以及重量
  let stdFormulaDatas = stdFormulaDataList.value || []
  productSteps.forEach((item: any) => {
    let findItem = stdFormulaDatas.find(
      (row: any) => row.materialId == item.materialId
    )
    if (findItem) {
      item.temperatureRequired = findItem.temperatureRequired ? 1 : 0
      item.seq = findItem.step || item.seq
      item.sort = findItem.index || item.sort
      item.value = findItem.value || item.value
      item.maxTemperature = findItem.maxTemperature || item.maxTemperature
      item.minTemperature = findItem.minTemperature || item.minTemperature
    }
  })

  //处理规格数据
  console.log('specificationList.value: ')
  console.log(specificationList.value)

  let productSpecGroups = []
  let specifications = specificationList.value || []
  for (let item of specifications) {
    let newItem = {
      //编码
      specId: item.id,
      specNumber: item.number,
      number: item.number,
      name: item.name,
      //是否支持客制化用料选择
      enableCustomize: item.enableCustomize ? 1 : 0,
      //默认选中的子项
      defaultSelectedId: item.defaultSelectedId,
      specList: [],
    }

    let children = item.children || []
    newItem.specList = children
    for (let subItem of children) {
      subItem.specId = item.id
      subItem.enableCustomize = item.enableCustomize ? 1 : 0
      subItem.defaultSelectedId = item.defaultSelectedId
      subItem.defaultSelected = item.defaultSelectedId == subItem.id ? 1 : 0
    }
    productSpecGroups.push(newItem)
  }
  formData.productSpecGroups = productSpecGroups

  //处理规格数据
  let productRules = []
  for (let item of rulesFilterForStep5.value) {
    let left = item.left
    let right = item.right

    let ruleCondition = left.reduce((first: string, last: { id: number }) => {
      return first + '&&{cno}===' + `'${last.id}'`
    }, '')

    if (ruleCondition.length > 0) {
      ruleCondition = ruleCondition.substring(2)
    }

    for (let rightItem of right) {
      let newItem: any = {}
      newItem.stepSeq = rightItem.sort
      newItem.seq = rightItem.seq
      newItem.ruleCondition = ruleCondition
      newItem.productId = rightItem.productId
      newItem.materialId = rightItem.materialId
      newItem.operate = rightItem.operate
      newItem.extralValue = rightItem.extralValue
      newItem.value = rightItem.value
      newItem.finalValue = rightItem.finalValue
      newItem.valueType = rightItem.valueType
      newItem.remark = rightItem.remark
      productRules.push(newItem)
    }
  }
  formData.productRules = productRules

  // makeStepDataList.value;
  if (!addEditRef.value) return
  addEditRef.value.validate((valid, fields) => {
    if (valid) {
      if (form.id) {
        updateFormulamanage({
          ...formData,
          id: form.id,
        })
          .then((res) => {
            cancel()
            ElMessage({
              message: props.modelValue.title + '修改成功',
              type: 'success',
            })
            if (props.modelValue.refreshDataList) {
              props.modelValue.refreshDataList()
            }
          })
          .catch((err) => {
            ElMessage({
              message: err.msg || err,
              type: 'error',
            })
          })
        return
      }

      addFormulamanage(formData)
        .then((res) => {
          //to do
          // cancel()
          ElMessage({
            message: props.modelValue.title + '新增成功',
            type: 'success',
          })
          if (props.modelValue.refreshDataList) {
            props.modelValue.refreshDataList()
          }
        })
        .catch((err) => {
          ElMessage({
            message: err.msg || err,
            type: 'error',
          })
        })
    }
  })
}

/***
 * 取消弹框
 */
const cancel = () => {
  // to do
  props.modelValue.visible = false
}
</script>
<style lang="scss" scoped>
.form-item {
  display: flex;
  align-items: center;
  .el-form-item {
    flex: 1;
  }
}

.specification-item {
  margin: 10px 0px 10px 30px;
  background: #fff;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
  padding: 12px 20px;
  .title {
    font-weight: bold;
    margin-bottom: 12px;
  }
  .detail {
    margin-top: 12px;
    display: flex;
    align-items: center;
    .checkbox {
      margin-left: 30px;
      display: flex;
      align-items: center;
    }
  }
}
</style>
<style>
.is-process {
  color: #ff9900 !important; /* 例如，使用 Element Plus 的主题色 */
  .el-step__icon.is-text {
    color: #ff9900 !important; /* 例如，使用 Element Plus 的主题色 */
  }
  .is-text {
    color: #ff9900 !important; /* 例如，使用 Element Plus 的主题色 */
  }
}

.rule-section {
  border: 1px solid #ddd;
  font-size: 12px;
  border-radius: 8px;
  &:last-child {
    margin-top: 12px;
  }
  .title-field {
    display: flex;
    align-items: center;
    background-color: #f6f7f9;
  }
  .title {
    line-height: 40px;
    background-color: #f6f7f9;
    padding: 0 12px;
  }
  .first-content-field {
    padding-top: 12px;
  }
}

.content-field {
  &.change-rule {
    display: flex;
    align-items: stretch;
  }
  .space {
    height: 100%;
    width: 10px;
    background-color: red;
  }
  .left {
    flex: 1;
    overflow: auto;
    max-height: 400px;
    padding-left: 6px;
    padding-right: 6px;
    padding-top: 16px;
    max-width: 160px;
    min-width: 160px;
    border-right: 1px solid #ddd;

    &::-webkit-scrollbar {
      width: 6px;
    }
    &::-webkit-scrollbar-track {
      background-color: transparent;
    }
    .rule-item {
      padding: 6px 0;
      padding-left: 12px;
      border: 1px solid #eee;
      margin-bottom: 12px;
      border-radius: 6px;
      position: relative;
      &.selected {
        border: 1px solid #ff990033;
        background-color: #ff990022;
      }
      .remove-icon {
        height: 24px;
        width: 24px;
        position: absolute;
        right: -5px;
        top: -5px;
        cursor: pointer;
      }
    }
  }
  .right {
    flex: 1;
    padding-top: 12px;
    margin-left: 6px;
    overflow: auto;
    max-height: 400px;
    padding-bottom: 12px;
    padding-right: 6px;
  }
}
</style>
